package P150;

import java.util.*;

/**
 * @author LiangMu
 * @version \$Id: P46.java, v 0.1, 2024年07月06日 02:53 LiangMu Exp $$
 */
public class P46 {

    public int[][] merge(int[][] intervals) {
        if (intervals.length <= 1) {
            return intervals;
        }

        Arrays.sort(intervals, Comparator.comparingInt(v -> v[0]));

        List<int[]> list = new ArrayList<>();
        int[] last = intervals[0];
        for (int i = 1; i < intervals.length; i++) {
            int[] ints = intervals[i];
            int left = ints[0];
            if (left > last[1]) {
                list.add(last);
                last = ints;
                continue;
            }
            last[0] = Math.min(last[0], left);
            last[1] = Math.max(last[1], ints[1]);
        }
        list.add(last);

        return list.toArray(new int[0][0]);
    }

}
